<script setup name="login">
import { ref, reactive, computed, onActivated } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import { CODE_WAIT_TIME } from '@/constants/index';
import * as userApi from '@/api/user';
import * as strategy from '@/constants/strategy';
import { throttle } from 'lodash';


// 路由
const router = useRouter();
const route = useRoute();
const checkedPassword = localStorage.getItem('checkedPassword') === 'true' || true;
const account = localStorage.getItem('account') || '';
const password = localStorage.getItem('password') || '';

const store = useStore();
// 短信倒计时
const timeDown = ref(CODE_WAIT_TIME);
// 短信显示隐藏
const showSms = ref(true);
// 登录于二维码切换
const loginFrame = ref(true);
// 账号登录表单dom
const loginForm = ref(null);
// 账号表单
const login = reactive({
  account: checkedPassword ? account : '',
  password: checkedPassword ? password : '',
  checkedPassword: checkedPassword,
  checkedOk: '',
});
// 手机号表单
const mobilePhone = reactive({
  mobile: '',
  code: '',
  checkedOk: '',
});
// 密码显示隐藏
const showPassword = ref(false);
// 账号验证
const validateAccount = (rule, value, callback) => {
  if (!strategy.ACCOUNT.test(value.trim())) {
    callback(new Error('账号格式错误 应为字母开头 共6-20个字符'));
  }
  callback();
};
// 手机号验证
const validateMobile = (rule, value, callback) => {
  if (!strategy.MOBILE.test(value.trim())) {
    callback(new Error('请输入正确的手机号'));
  }
  callback();
};
// 协议验证
const validateCheckedOk = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请选择登录协议'));
  }
  callback();
};
// 验证表单
const rules = reactive({
  account: [
    { validator: validateAccount, trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码' },
  ],
  checkedOk: [
    { validator: validateCheckedOk, trigger: 'change' },
  ],
  mobile: [
    { validator: validateMobile, trigger: 'blur' },
  ],
});

// 登录
function onLogin() {
  loginForm.value.validate((valid) => {
    if (valid) {
      if (login.checkedOk) {
        store.dispatch('user/login', {
          account: login.account,
          password: login.password,
        })
          .then((res) => {
            if (login.checkedPassword) {
              localStorage.setItem('checkedPassword', true);
              localStorage.setItem('account', login.account);
              localStorage.setItem('password', login.password);
            }
            localStorage.setItem('account', login.account);
            ElMessage({
              message: res.msg,
              type: 'success',
            });
            router.push({
              path: '/',
            });
          })
          .catch((err) => {
            localStorage.setItem('password', '');
          });
      }
    } else {
      return false;
    }
  });
}
// 密码显示隐藏
function onSwitcHover() {
  showPassword.value = !showPassword.value;
}
// const timer = setInterval(() => {
//   timeDown.value--;
//   console.log(timeDown.value);
// }, 1000);

// 短信和手机号码切换
function onChange() {
  showSms.value = !showSms.value;
}

// 切换登录于短信
function onAccount() {
  loginFrame.value = true;
}

// 切换登录于二维码
function onMessage() {
  loginFrame.value = false;
}
// 发送验证码
const sendCodeWithCheckSuccess = throttle(() => {
  let timer = null;
  userApi.loginCode(mobilePhone.mobile)
    .then((res) => {
      ElMessage({
        message: res,
        type: 'success',
      });
    })
    .catch((err) => {
      sendCodeWithCheckSuccess.cancel();
      clearInterval(timer);
      timeDown.value = CODE_WAIT_TIME;
      console.log(err);
      ElMessage({
        message: err,
        type: 'error',
      });
    });
  timeDown.value = CODE_WAIT_TIME - 1;
  timer = setInterval(() => {
    timeDown.value--;
    if (timeDown.value < 1) {
      clearInterval(timer);
    }
  }, 1000);
}, CODE_WAIT_TIME * 1000);

function sendCode() {
  if (!strategy.MOBILE.test(mobilePhone.mobile)) {
    return;
  }
  sendCodeWithCheckSuccess();
}

// 手机号登录
function onMobileLogin() {
}

// 切过来打印
// onActivated(() => {
//   console.log('123');
// });

// 切走打印
// onDeactivated(() => {
//   console.log('456');
// });


</script>

<template>
  <div class="main">
    <div class="header">
      <div>
        <a href="#">
          <img src="http://erabbit.itheima.net/img/logo.0940ebb5.png" />
        </a>
      </div>
      <div class="login">
        <h3>欢迎登录</h3>
      </div>
      <div class="home">
        <a href="#">进入网站首页</a>
        <el-icon><ArrowRight /></el-icon>
        <el-icon><ArrowRight /></el-icon>
      </div>
    </div>

    <div class="section">
      <div class="login-container">
        <div class="login-header">
          <div
            class="login-size"
            @click="onAccount"
          >账号登录</div>
          <div @click="onMessage">扫码登录</div>
        </div>
        <div
          class="verification"
          v-show="loginFrame"
        >
          <div class="message">
            <a
              v-show="showSms"
              @click="onChange()"
            >
              <el-icon class="Message-icon"><Message /></el-icon>
              <span>使用短信登录 </span>

            </a>
            <a
              v-show="!showSms"
              @click="onChange()"
            >
              <el-icon><User /></el-icon>
              <span>使用账号登录</span>
            </a>
          </div>
          <!-- 账号登录 -->
          <el-form
            :model="login"
            :rules="rules"
            ref="loginForm"
            v-show="showSms"
          >
            <div class="user">
              <el-form-item prop="account">
                <el-input
                  v-model="login.account"
                  placeholder="请输入用户名"
                  class="input-with-select"
                >
                  <template #prepend>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </div>
            <el-form-item prop="password">
              <!-- 密码 -->
              <el-input
                v-model="login.password"
                v-show="showSms"
                placeholder="请输入密码"
                class="input-with-select"
                :type="showPassword ? 'text' : 'password'"
              >
                <template #prepend>
                  <el-icon><Lock /></el-icon>
                </template>
                <template #append>
                  <span
                    class="switchover"
                    @click="onSwitcHover"
                    v-show="!showPassword"
                  >
                    <el-icon><Hide /></el-icon>
                  </span>
                  <span
                    class="switchover"
                    @click="onSwitcHover"
                    v-show="showPassword"
                  >
                    <el-icon><View /></el-icon>
                  </span>
                </template>

              </el-input>
            </el-form-item>
            <div class="clause">
              <div>
                <el-checkbox
                  v-model="login.checkedPassword"
                >记住密码</el-checkbox>
              </div>
              <div>
                <el-form-item prop="checkedOk">
                  <el-checkbox
                    v-model="login.checkedOk"
                  >
                    我以同意
                    <a href="">《隐私条款》</a>
                    和
                    <a href="">《服务条款》</a>
                  </el-checkbox>
                </el-form-item>
              </div>
            </div>
          </el-form>

          <!-- 号码登录 -->
          <el-form
            :model="mobilePhone"
            ref="loginMobileForm"
            :rules="rules"
            v-show="!showSms"
          >
            <div class="user">
              <el-form-item prop="mobile">
                <el-input
                  v-model="mobilePhone.mobile"
                  placeholder="请输入手机号"
                  class="input-with-select"
                >
                  <template #prepend>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </div>
            <el-form-item prop="code">
              <el-input
                v-model="mobilePhone.code"
                placeholder="请输入验证码"
                class="input-with-select"
                type="text"
              >
                <template #prepend>
                  <el-icon><Lock /></el-icon>
                </template>
                <template #append>
                  <span @click="sendCode">{{ timeDown < 60 ? timeDown : '发送验证码' }}</span>
                </template>
              </el-input>
            </el-form-item>

            <div class="clause">
              <div>
                <el-form-item prop="checkedOk">
                  <el-checkbox
                    v-model="mobilePhone.checkedOk"
                  >
                    我以同意
                    <a href="">《隐私条款》</a>
                    和
                    <a href="">《服务条款》</a>
                  </el-checkbox>
                </el-form-item>
              </div>
            </div>

          </el-form>
          <el-button
            @click="() => showSms? onLogin(): onMobileLogin()"
            :disabled="!login.checkedOk"
          >
            登录
          </el-button>
        </div>

        <div
          v-show="!loginFrame"
        >
          1111
        </div>

      </div>
    </div>

    <div class="bottom">
      <a href="#">关于我们</a>
      <a href="#">帮助中心</a>
      <a href="#">售后服务</a>
      <a href="#">配送与验收</a>
      <a href="#">商务合作</a>
      <a href="#">搜索推荐</a>
      <a href="#">友情链接</a>
    </div>

    <div class="sign">
      CopyRight © 小兔鲜儿
    </div>
  </div>
</template>

<style lang="scss" scoped>
$a: #27ba9b;
$b: #e5e5e5;
$c: #333;
$d: #069;
$e: #999;
// input框图标颜色
$f: #e1dfdf;
$white: white;

  .main {
    .header {
      display: flex;
      align-items: flex-end;
      padding: 24px;


      img {
        display: inline-block;
        width: 200px;
        // background-image: url('http://erabbit.itheima.net/img/logo.0940ebb5.png');
        background-size: cover;
      }

      .login {
        flex: 1;
      }

      .home {
        padding-right: 24px;

        a {
          display: inline-block;
          padding-bottom: 20px;
          // 取消下划线
          text-decoration: none;
          color: $c;
        }
      }

      h3 {
        padding-left: 20px;
        color: $c;
        font-weight: normal;
      }
    }

    .section {
      min-width: 1200px;
      background-image: url('http://erabbit.itheima.net/img/login-bg.696efec3.png');
      background-position: 50% 50%;
      height: 488px;

      .login-container {
        position: absolute;
        width: 380px;
        height: 400px;
        background-color: $white;
        box-sizing: border-box;
        right: 15%;
        top: 30%;

        .login-header {
          position: relative;
          display: flex;
          justify-content: space-between;
          padding: 0 40px;
          border-bottom: 1px solid $b;
          height: 50px;
          line-height: 50px;

          .login-size::before {
            content: '';
            display: inline-block;
            width: 1px;
            height: 15px;
            background-color: $b;
            position: absolute;
            right: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
          }
        }

        .login-header.active {
          color: $a;
          font-weight: 700;
        }

        .verification {
          padding: 0 40px;
          .message {
            padding: 16px 0;

            text-align: right;
            a {
              display: inline-block;
              // 取消下划线
              text-decoration: none;
              color: $a;
              cursor: pointer;

              span {
                font-size: 14px;
              }
            }

            .Message-icon {
              vertical-align: -10%;
              padding-right: 4px;
            }
          }

          .user {
            padding-bottom: 25px;
          }

          .clause {
            font-size: 14px;
            padding: 18px 0;

            div {
              height: 25px;
            }

            a {
              display: inline-block;
              color: $d;
              height: 14px;
              text-decoration: none;
            }

          }

          // 密码显示隐藏
          .switchover {
            cursor: pointer;
          }

          ::v-deep(.el-input-group__prepend) {
            padding: 0 10px;
            background-color: $f;
          }
        }
      }
    }

    .bottom {
      display: flex;
      justify-content: center;
      padding-top: 24px;

      a {
        position: relative;
        display: inline-block;
        color: $e;
        font-size: 14px;
        padding: 0 12px;
        text-decoration: none;
      }

      a::after {
        position: absolute;
        content: '';
        display: inline-block;
        width: .5px;
        height: 15px;
        background-color: $e;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .sign {
      font-size: 14px;
      text-align: center;
      color: $e;
      padding-top: 18px;
      padding-bottom: 24px;
    }
  }

  ::v-deep(.el-icon svg) {
    color: #27ba9b;
    height: 12px;
  }

  ::v-deep(.el-icon) {
    width: 12px;
  }

  ::v-deep(.el-button) {
    width: 100%;
    background-color: #27ba9b;
    height: 40px;
    color: $white;
  }

</style>
